package com.bio.service.impl;

import java.io.Serializable;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.bio.dao.Dao;
import com.bio.dao.attachment.AttachmentDAO;
import com.bio.entity.attachemnt.BaseObjectAttachment;
import com.bio.exception.OperationException;
import com.bio.service.Service;
import com.bio.utils.Pager;
import com.bio.utils.Pagination;

@Transactional
public class AbstractService<E extends Serializable, D extends Dao<E>>
		implements Service<E> {

	protected D dao;
	
	public AbstractService(D dao) {
		this.dao = dao;
	}

	public E get(Serializable id) {
		return this.dao.get(id);
	}

	public void remove(Serializable id) throws OperationException {
		try {
			E e = dao.get(id);
			if(e instanceof BaseObjectAttachment){
				BaseObjectAttachment object = (BaseObjectAttachment)e;
				String attachmentsInfo = object.getAttachmentsInfo();
				//判断该对象是否有附件，如果有一并删除
				if(StringUtils.isNotEmpty(attachmentsInfo)){
					ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
					AttachmentDAO attachmentDAO = (AttachmentDAO)ctx.getBean("attachmentDAO");
					JSONArray jArray = JSONArray.fromObject(attachmentsInfo);
					List<JSONObject> jsons = JSONArray.toList(jArray, JSONObject.class);
					for(JSONObject jObject : jsons){
						Long attId = jObject.getLong("attId");
						attachmentDAO.remove(attId);
					}
				}
			}
			this.dao.remove(id);
		} catch (Exception e) {
			throw new OperationException(e);
		}

	}

	public E save(E obj) throws OperationException {
		try {
			return this.dao.save(obj);
		} catch (Exception e) {
			throw new OperationException(e);
		}
	}

	public D getDao() {
		return dao;
	}

	public Pager<E> findAllByPager(Pagination pagination) {	
		return dao.findAllByPager(pagination);
	}

	public Pager<E> findAllByPagerNoCache(Pagination pagination) {
		return dao.findAllByPagerNoCache(pagination);
	}
}
